import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Tabs,
  Space,
  Button,
  Form,
  Row,
  Col,
  Input,
  message,
  Select,
  DatePicker,
  Checkbox,
  notification,
  Modal,
  Table,
} from 'antd';
import { connect } from 'umi';
import {
  PlusOutlined,
  CloseOutlined,
  SyncOutlined,
  ExclamationCircleOutlined,
  CheckOutlined,
} from '@ant-design/icons';
import ShipDtlSo from '../part/components/shipDtlSo';
import request from '@/utils/request';
import moment from 'moment';
import CateComp from '@/components/CategoryComponent';
import IconFont from '@/components/Iconfont';
import { EmpSelect } from '@/components/FormItemSelect';

const { TabPane } = Tabs;
const { Search } = Input;
const { confirm } = Modal;
const apiURL = '/api/services/app/ShipHead/';
const apiURLDtl = '/api/services/app/ShipDtl/';
const currentControl = 'ShipHead';
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      dataSource: [],
      data: {},
      defTab: '1',
      pageIndex: 1,
      pageSize: 10,
      optionCust: [],
      selectedRowKeys: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchDatas();
    this.fetchCusts();
    this.queryAllOrder();
  }
  queryAllOrder = () => {
    //获取所有退单列表接口
  }
  queryOrderDetial = () => {
    //获取退单明细接口
  }
  fetchDatas = () => {
    const { pageIndex, pageSize, keywords } = this.state;
    this.setState({ loading2: true });
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords },
        control: currentControl,
      })
      .then(() => {
        var result = this.props.response.result;
        if (result) {
          this.setState({
            dataSource: result.items,
            totalCount: result.totalCount,
            loading2: false,
          });
        }
      });
  };
  fetchCusts = () => {
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/getAll',
        payload: { SkipCount: 0, MaxResultCount: 9999 },
        control: 'Customers',
      })
      .then(() => {
        var result = this.props.response.result;
        this.setState({ optionCust: result.items });
      });
  };
  onFinish = (values: any) => {
    this.save(values.ShipHead);
  };
  resetForm = () => {
    let data = { packNum: '0', id: '0' };
    this.formRef.current.resetFields();
    this.formRef.current.setFieldsValue({ ShipHead: data });
    this.setState({ data });
  };
  save = (model: any) => {
    var act = 'Modify';
    var method = 'POST';
    model.shipDate = model.shipDate?.format('YYYY-MM-DD');
    model.entryDate = model.entryDate?.format('YYYY-MM-DD');
    if (model.id === '0') {
      act = 'New';
      model.id = undefined;
      model.shipStatus = '未结';
    }

    request(apiURL + act, {
      method,
      data: model
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
          var ShipHead = response.result.data;
          if (ShipHead.shipDate) ShipHead.shipDate = moment(ShipHead.shipDate);
          if (ShipHead.entryDate) ShipHead.entryDate = moment(ShipHead.entryDate);
          this.formRef.current.setFieldsValue({ ShipHead });
          this.setState({ data: { data: ShipHead } });
          this.fetchDatas();
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        this.setState({ loading: false });
      }
    });
  };
  tabSwitch = (key: any) => {
    this.setState({ defTab: key });
  };
  getObj = (value: any) => {
    if (!value) {
      return;
    }
    this.setState({ loading: true });
    request(apiURL + 'GetByNum', {
      method: 'GET',
      params: { num: value }
    }).then((response) => {
      if (response) {
        if (response.success) {
          var result = response.result;
          var ShipHead = result.data;
          if (ShipHead) {
            if (ShipHead.shipDate) ShipHead.shipDate = moment(ShipHead.shipDate);
            if (ShipHead.entryDate) ShipHead.entryDate = moment(ShipHead.entryDate);
            this.formRef.current.setFieldsValue({ ShipHead });
            this.setState({ data: result, visible: false, loading: false });
          }
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        this.setState({ loading: false });
      }
    });
  };
  delObj = () => {
    const { data } = this.state;
    console.log(data);

    if (data.data) {
      let _this = this;
      confirm({
        title: '警告',
        icon: <ExclamationCircleOutlined />,
        content: '删除后将不可恢复，确定删除？',
        onOk() {
          _this.props
            .dispatch({
              type: 'Abp/delete',
              payload: { id: data.data.id },
              control: currentControl,
            })
            .then(() => {
              _this.fetchDatas();
              _this.resetForm();
            });
        },
      });
    }
  };
  switchModal = (visible: boolean, record: any = null) => {
    const { data } = this.state;
    if (record == null) {
      record = {
        packNum: data.data?.packNum,
      };
    }
    this.setState({ visible, record });
  };
  shipDtlPo: any = ShipDtlSo;
  onRef = (ref: any) => {
    this.shipDtlPo = ref;
  };
  onSearch = (value: any) => {
    var keywords = this.state.keywords;
    keywords = value;
    this.setState({ keywords }, () => {
      this.fetchDatas();
    });
  };
  CustSelChange = (e: any) => {
    var obj = this.state.optionCust.filter((o: any) => o.custNum == e)[0];
    let ShipHead: any = {};
    ShipHead.ffCountry = obj.country;
    ShipHead.ffState = obj.state;
    ShipHead.ffCity = obj.city;
    ShipHead.ffAddress1 = obj.contAddress;
    this.formRef.current.setFieldsValue({ ShipHead });
  };
  delDtl = () => {
    const { selectedRowKeys, data } = this.state;
    let _this = this;
    this.setState({ loading: true });
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.props
          .dispatch({
            type: 'Abp/delPatch',
            payload: selectedRowKeys,
            control: 'ShipDtl',
          })
          .then(() => {
            let _data = data;
            _data.details = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
            _this.setState({ data: _data, loading: false });
          });
      },
    });
  };
  completeDtl = () => {
    const { selectedRowKeys, data } = this.state;
    let arrs: any = [];
    let lists = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) >= 0);
    lists.forEach((item: any) => {
      arrs.push({
        packNum: item.packNum,
        packLine: item.packLine,
      });
    });
    request(apiURLDtl + 'Complete', {
      method: 'POST',
      data: arrs
    }).then((response) => {
      if (response.success) {
        let result = response.result;
        if (result.success) {
          message.success('出货成功');
          this.getObj(arrs[0].packNum);
        } else {
          message.error(result.message);
        }
      } else {
        message.error(response.error.message);
      }
    });
  };
  render() {
    const layout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const {
      data,
      defTab,
      record,
      dataSource,
      pageSize,
      totalCount,
      loading,
      loading2,
      selectedRowKeys,
    } = this.state;
    const columns = [
      {
        title: '退单 ',
        dataIndex: 'packNum',
      },
      {
        title: '项目',
        dataIndex: 'packLine',
      },
      {
        title: '物料编码',
        dataIndex: 'partNum',
      },
      {
        title: '物料描述',
        dataIndex: 'partDescription',
      },
      {
        title: '退货数量',
        dataIndex: 'ourJobShipQty',
      },
      {
        title: '单位',
        dataIndex: 'ium',
      },
      {
        title: '完成',
        dataIndex: 'shipCmpl',
        key: 'shipCmpl',
        render: (text: boolean) => <Checkbox checked={text} />,
      },
    ];
    const columns2 = [
      {
        width: 30,
        render: () => <IconFont type="icon-database" />,
      },
      {
        title: '退货单号',
        dataIndex: 'packNum',
      },
      {
        title: '退货日期',
        dataIndex: 'shipDate',
        render: (text: string) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
      },
      {
        title: '退货来源',
        dataIndex: 'shipPerson',
      },
      {
        title: '状态',
        dataIndex: 'shipStatus',
      },
    ];
    const optionCust = this.state.optionCust?.map((d: any) => {
      return (
        <Select.Option value={d.custNum} key={d.id}>
          {d.customerName}
        </Select.Option>
      );
    });
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
      },
    };
    return (
      <PageHeaderWrapper title={false}>
        <Form {...layout} ref={this.formRef} onFinish={this.onFinish}>
          <Card
            title="销售退货"
            extra={
              <Space>
                <Button key="1" type="primary" icon={<PlusOutlined />} onClick={this.resetForm}>
                  新建
                </Button>
                <Button key="2" type="primary" htmlType="submit">
                  保存
                </Button>
                <Button
                  key="4"
                  type="dashed"
                  danger
                  icon={<CloseOutlined />}
                  onClick={this.delObj}
                  disabled={data.id === '0'}
                >
                  删除
                </Button>
              </Space>
            }
          >
            <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={this.tabSwitch}>
              <TabPane tab="汇总" key="1">
                <Row>
                  <Col span={9}>
                    <Form.Item
                      name={['ShipHead', 'packNum']}
                      label="退货单号"
                      rules={[{ required: true, message: '退货单号必填' }]}
                    >
                      <Input
                        style={{ width: 200 }}
                        onBlur={(e: any) => this.getObj(e.target.value)}
                        placeholder="请输入退货单号"
                      />
                    </Form.Item>
                    <Form.Item
                      name={['ShipHead', 'shipDate']}
                      label="退货日期"
                      rules={[{ required: true }]}
                    >
                      <DatePicker />
                    </Form.Item>
                    <EmpSelect
                      showSearch
                      width={200}
                      name={['ShipHead', 'shipPerson']}
                      label="出货人"
                    />
                    <CateComp
                      layout="ShipVia"
                      width={200}
                      name={['ShipHead', 'shipViaCode']}
                      label="运输方法"
                    />
                    <Form.Item
                      name={['ShipHead', 'custNum']}
                      label="选择客户"
                      rules={[{ required: true, message: '客户必填' }]}
                    >
                      <Select
                        style={{ width: 280 }}
                        placeholder="请选择"
                        onChange={this.CustSelChange}
                      >
                        {optionCust}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name={['ShipHead', 'shipComment']} label="退货备注">
                      <Input.TextArea />
                    </Form.Item>

                    <Form.Item label="退货地区" style={{ marginBottom: 0 }}>
                      <Input.Group compact>
                        <Form.Item
                          name={['ShipHead', 'ffCountry']}
                          rules={[{ required: true, message: '国家必填' }]}
                        >
                          <Input placeholder="国家" />
                        </Form.Item>
                        <Form.Item
                          name={['ShipHead', 'ffState']}
                          rules={[{ required: true, message: '省/州必填' }]}
                        >
                          <Input placeholder="省/州" />
                        </Form.Item>
                        <Form.Item
                          name={['ShipHead', 'ffCity']}
                          rules={[{ required: true, message: '城市必填' }]}
                        >
                          <Input placeholder="城市" />
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item
                      label="详细地址"
                      name={['ShipHead', 'ffAddress1']}
                      rules={[{ required: true, message: '详细地址必填' }]}
                    >
                      <Input />
                    </Form.Item>
                  </Col>
                </Row>
              </TabPane>
              <TabPane tab="退单明细" key="2">
                <Table
                  rowKey="id"
                  size="small"
                  columns={columns}
                  loading={loading}
                  dataSource={data.details}
                  rowSelection={rowSelection}
                  footer={() => (
                    <Space>
                      <Button
                        block
                        type="dashed"
                        icon={<PlusOutlined />}
                        onClick={() => this.switchModal(true)}
                      >
                        新建明细
                      </Button>
                      <Button
                        type="primary"
                        icon={<CheckOutlined />}
                        onClick={this.completeDtl}
                        disabled={selectedRowKeys.length <= 0}
                      >
                        全部完成
                      </Button>
                      <Button
                        type="dashed"
                        danger
                        icon={<CloseOutlined />}
                        onClick={this.delDtl}
                        disabled={selectedRowKeys.length <= 0}
                      >
                        删除选中
                      </Button>
                    </Space>
                  )}
                  onRow={(record) => {
                    return {
                      onDoubleClick: (event) => {
                        this.switchModal(true, record);
                      },
                    };
                  }}
                />
              </TabPane>
            </Tabs>
          </Card>
        </Form>
        <Card
          title="所有退单"
          extra={
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="ghost"
                onClick={() => this.fetchDatas()}
                loading={loading2}
                icon={<SyncOutlined />}
              ></Button>
              <Search
                style={{ width: 240 }}
                placeholder="输入关键词搜索"
                onSearch={(value) => this.onSearch(value)}
              />
            </Space>
          }
        >
          <Table
            rowKey="id"
            size="small"
            columns={columns2}
            loading={this.state.loading2}
            dataSource={dataSource}
            pagination={{
              onChange: (page) => {
                this.setState({ pageIndex: page }, () => {
                  this.fetchDatas();
                });
              },
              pageSize,
              total: totalCount,
            }}
            onRow={(record) => {
              return {
                onDoubleClick: (event) => {
                  this.getObj(record.packNum);
                },
              };
            }}
          />
        </Card>
        <Modal
          title="出货明细"
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={() => this.switchModal(false)}
          footer={false}
        >
          <ShipDtlSo onRef={this.onRef} data={record} refreshData={this.getObj} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
